package com.zzyl.intercept;

import com.zzyl.constant.JwtConstants;
import com.zzyl.properties.JwtProperties;
import com.zzyl.utils.HttpStatus;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.StringUtils;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Service
public class MemberInterceptor implements HandlerInterceptor {


    @Autowired
    private JwtProperties jwtproperties;
    /**
     * 进入controller之前调用
     * 如果返回false 不调用controller
     * 如果返回true 会调用controller
     * */



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取header种的token，key：authorization
        String token = request.getHeader(JwtConstants.TOKEN_KEY);
        // 判断token是否为空
        if (StringUtils.isEmpty(token)) {
            // 如果token是空， 返回401
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
        // 如果token不是空
        // 解析token
        try {
            Claims claims = JwtUtil.parseJWT(jwtproperties.getBase64EncodedSecretKey(), token);
            // 如果解析token成功，获取token种的memberId
            Long memberId = claims.get(JwtConstants.MEMBER_ID, Long.class);
            if (memberId == null || memberId <= 0) {
                response.setStatus(HttpStatus.UNAUTHORIZED);
                return false;
            } else {
                // 把memberId保存到ThreadLocal
                UserThreadLocal.set(memberId);
                log.info("保存用户id到TL：{}", memberId);
                return true;
            }
        } catch (Exception e) {
            // 如果解析token失败， 返回401
            log.error(e.getMessage(), e);
            response.setStatus(HttpStatus.UNAUTHORIZED);
            return false;
        }
    }
    /**
     * controller执行完成以后会调用
     * 如果controller执行出了异常，此方法不调用
     * */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    /**
     * controller执行完成以后，视图渲染完成以后会调用
     * 如果controller执行出了异常，此方法仍然调用
     * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
